package com.dylan.历史.多线程.并发编程的艺术.编程基础.模拟连接池;

import java.util.LinkedList;

/**
 * Created by Dylan on 2018/9/18.
 */
public class ConnectionPool {

    private final LinkedList<Connection> pool = new LinkedList<>();

    public ConnectionPool(int initialSize) {
        for (int i = 0; i < initialSize; i++) {
            pool.add(new Connection("Connection-" + i));
        }
    }

    public Connection fetch(long millis) throws InterruptedException {
        synchronized (pool) {
            if (millis < 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
            } else {
                long future = System.currentTimeMillis() + millis;
                long remaining = millis;
                while (pool.isEmpty() && remaining > 0) {
                    pool.wait(remaining);
                    remaining = future - System.currentTimeMillis();
                }
            }
            return pool.isEmpty() ? null : pool.poll();
        }
    }

    public void release(Connection connection) {
        if (connection != null) {
            synchronized (pool) {
                pool.offer(connection);
                pool.notifyAll();
            }
        }
    }
}
